package com.jincp.image.load.glide_loder;

import android.content.Context;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.jincp.image.load.ImageLoader;
import com.jincp.image.load.ImageLoaderOptions;

/**
 * Created by admin on 2017/3/23.
 */

public class GlideImageLoader implements ImageLoader {

    private static volatile Context context;

    @Override
    public void init(Context context) {
        GlideImageLoader.context = context.getApplicationContext();
    }

    @Override
    public <T> void displayImage(T t, ImageView imageView, ImageLoaderOptions options) {
        if (imageView == null) return;
        //装配附加参数
        RequestOptions requestOptions = loadOptions(options);
        // TODO GlideApp
        //装配基本的参数
        GlideApp.with(context).load(t).apply(requestOptions).into(imageView);
    }

    @Override
    public <T> void displayGif(T t, ImageView imageView) {
        // TODO GlideApp
        GlideApp.with(context).asGif2().load(t).into(imageView);//采用Giflib来解码GIF
    }

    @Override
    public void cleanCache() {
        // 主线程操作
        Glide.get(context).clearMemory();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(context).clearDiskCache();
            }
        }).start();
    }

    //这个方法用来装载由外部设置的参数
    @SuppressWarnings("CheckResult")
    private RequestOptions loadOptions(ImageLoaderOptions options) {
        RequestOptions requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .dontAnimate()
                .fitCenter()
                .placeholder(options.getDefaultDrawable())
                .error(options.getErrorDrawable())
                .priority(Priority.HIGH);
        if (options.getReWidth() != 0 || options.getReHeight() != 0) {
            requestOptions.override(options.getReWidth(), options.getReHeight());
        }
        if (options.getImageShape() == ImageLoaderOptions.SHAPE_CIRCLE) {
            requestOptions.transform(new GlideTransformCircle(options.getBorderSize(), options.getBorderColor()));
        } else if (options.getImageShape() == ImageLoaderOptions.SHAPE_ROUND) {
            requestOptions.transform(new GlideTransformRound(options.getRoundRadius(), options.getRoundType()));
        }
        return requestOptions;
    }
}
